import gobject

from db import db
from fvutil.managers import objectmanager
from fvutil import fvcon
from util import config

import random
from presence import ps

class TextPresence(ps.ObjectPresence):

    def __init__(self, oid, name):
        ps.ObjectPresence.__init__(self, oid, name)
        
class TextManager(objectmanager.ObjectManager):
    
    __gsignals__ = {
            'created_text' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_INT, gobject.TYPE_INT,)),
            'received_text' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                    (gobject.TYPE_PYOBJECT,)),
    }
    
    def __init__(self, async, my_id):
        objectmanager.ObjectManager.__init__(self, fvcon.TEXT, my_id)
        self.__async = async
        self.__path = config.get('async.folders', str(fvcon.TEXT))
    
    def send(self, data):
        """
            Sends a text message.
            
            @param data
            A dictionary containing 
        """
        tags = data['tags']
        text = data['text']
        dests = data['recipients']
        id = random.randint(1,100000)
        path = self.__path + '/' + str(id) + '.text'
        f = open(path, mode='wa')
        f.write(text)
        f.close()
        
        meta = {fvcon.TAGS: tags}
        header = self.__async.send_message(path, fvcon.TEXT, dests, meta)
        self.add(header)
        print header.mid, fvcon.TEXT
        self.emit('created_text', header.mid, fvcon.TEXT)
        
    def receive(self, header):
        self.add(header)
        flash = self.to_flash(header)
        self.emit('received_text', flash )
        
    def to_flash(self, header):
        path = header.get_file_path()
        f = open(path, mode='ra')
        text = f.read()
        f.close()
        return {'type':fvcon.TEXT, 'subcommand':fvcon.ADD, 'id':header.mid, 'label':header.meta[fvcon.TAGS], 'time':header.created, 'authorID':header.src, 'tags':header.meta[fvcon.TAGS], 'text':text, 'src':header.src}
        
            
gobject.type_register(TextManager)